﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Application.BankCard.Dto;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using System.Data.Entity;
using RXY_Mall.Domain;

namespace RXY_Mall.Application.BankCard
{
    public class BankCardService : RXY_MallAppServiceBase, IBankCardService
    {
        public async Task<Response<int>> AddorEditBankCard(int managerId, int shopId, BankCardInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.bank_name))
            {
                errorList.Append("开户行不能为空；</br>");
            }
            if (input.bank_name=="-1")
            {
                errorList.Append("请选择开户行；</br>");
            }
            if (string.IsNullOrEmpty(input.bank_cardno))
            {
                errorList.Append("卡号不能为空；</br>");
            }
            if (input.types == 1&&(string.IsNullOrEmpty(input.bank_face_card)|| string.IsNullOrEmpty(input.bank_opposite_card)))
            {
                errorList.Append("请上传身份信息；</br>");
            }
            if (string.IsNullOrEmpty(input.company_permission) )
            {
                errorList.Append("请上传凭证；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            var model = db.gw_shop_bankcards.FirstOrDefault(i => i.shop_id == shopId);
            if (input.id<=0&&model != null)
            {
                input.id = model.id;
            }
            if (input.id > 0)
            {
                var entity = db.gw_shop_bankcards.FirstOrDefault(i => i.id == input.id&&i.shop_id==shopId);
                if (entity != null)
                {
                    if (entity.status == 0)
                    {
                        entity.company_permission = input.company_permission == null ? "" : input.company_permission;
                        if (entity.types==0)
                        {
                            entity.company_name = input.company_name;
                        }
                        entity.mobile_number = input.mobile_number == null ? "" : input.mobile_number;
                        entity.company_permission = input.company_permission == null ? "" : input.company_permission;
                        entity.bank_name = input.bank_name;
                        entity.bank_cardno = input.bank_cardno;
                        //entity.types = (byte)input.types;
                        entity.bank_branch = input.bank_branch == null ? "" : input.bank_branch;
                        entity.account_holder = input.account_holder == null ? "" : input.account_holder;
                        entity.bank_province = input.bank_province;
                        entity.bank_city = input.bank_city;
                        entity.bank_country = input.bank_country;
                        entity.remark = input.remark == null ? "" : input.remark;
                        entity.bank_face_card = input.bank_face_card == null ? "" : input.bank_face_card;
                        entity.bank_opposite_card = input.bank_opposite_card == null ? "" : input.bank_opposite_card;
                        await db.SaveChangesAsync();
                        LogHelper.WriteLog("商家管理员" + managerId + "修改：店铺"+shopId+"银行账户" + entity.id +"信息");
                        return ReturnSuccess<int>(entity.id);
                    }
                    else
                    {
                        return ReturnError<int>("已审核通过，无法更改！");
                    }
                }
                return ReturnError<int>("账户信息不存在");
            }
            else
            {
                if (shopId> 0)
                {
                    var entity = new gw_shop_bankcard()
                    {
                        shop_id = shopId,
                        company_name = input.company_name,
                        mobile_number = input.mobile_number == null ? "" : input.mobile_number,
                        company_permission = input.company_permission == null ? "" : input.company_permission,
                        bank_name = input.bank_name,
                        bank_cardno = input.bank_cardno,
                        types = (byte)input.types,
                        bank_branch = input.bank_branch == null ? "" : input.bank_branch,
                        account_holder = input.account_holder == null ? "" : input.account_holder,
                        bank_province = input.bank_province,
                        bank_city = input.bank_city,
                        bank_country = input.bank_country,
                        bankaddress = input.bankaddress == null ? "" : input.bankaddress,
                        remark = input.remark == null ? "" : input.remark,
                        bank_face_card = input.bank_face_card == null ? "" : input.bank_face_card,
                        bank_opposite_card = input.bank_opposite_card == null ? "" : input.bank_opposite_card,
                        add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        status = 0
                    };
                    if (entity.types==0)
                    {
                        entity.status = 1;
                    }
                    var addModel = db.gw_shop_bankcards.Add(entity);
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        LogHelper.WriteLog("商家管理员" + managerId + "添加：店铺" + shopId + "银行账户" + addModel.id);
                        return ReturnSuccess<int>(addModel.id);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                else
                {
                    return ReturnError<int>("商家ID错误");
                }
            }
        }

        public async Task<Response<int>> CheckShopBankCard(int managerId,int id, int status, string remark)
        {
            var model = db.gw_shop_bankcards.FirstOrDefault(i => i.id == id);
            if (model == null)
            {
                return ReturnError<int>("信息不存在");
            }
            if (status == 0|| model.status == (byte)status)
            {
                return ReturnError<int>("审核状态未改变");
            }
            if (status==1)
            {
                // 通知
                var message = new gw_message()
                {
                    user_id = 0,
                    shop_id = model.shop_id,
                    type = 5,
                    title = "银行卡审核成功通知",
                    summary = "您的银行账户申请已审核通过！",
                    content = "银行名称：" + model.bank_name ,
                    picture_url = "",
                    status = 1,
                    remark = "",
                    deleted = false,
                    add_time = DateTime.Now,
                };
                db.gw_messages.Add(message);
            }
            else if (status==2)
            {
                // 通知
                var message = new gw_message()
                {
                    user_id = 0,
                    shop_id = model.shop_id,
                    type = 5,
                    title = "银行卡审核失败通知",
                    summary = "您的银行账户申请被拒绝，请重新提交信息！",
                    content = "拒绝原因" + remark + "；银行名称：" + model.bank_name,
                    picture_url = "",
                    status = 1,
                    remark = "",
                    deleted = false,
                    add_time = DateTime.Now,
                };
                db.gw_messages.Add(message);
            }
            model.status = (byte)status;
            model.remark = remark;
            await db.SaveChangesAsync();
            LogHelper.WriteLog("管理员" + managerId + "审核：改变商家银行卡" + id + "状态为" + status);
            return ReturnSuccess<int>(1);
        }

        public BankCardDto GetBankCardInfo(int shopId)
        {
            var entity = new gw_shop_bankcard();
            //if (id>0)
            //{
            //    entity = db.gw_shop_bankcards.FirstOrDefault(i => i.id == id&&i.shop_id==shopId);
            //}
            //else
            //{
            entity = db.gw_shop_bankcards.FirstOrDefault(i => i.shop_id == shopId);
            //}
            if (null != entity)
            {
                return new BankCardDto()
                {
                    id = entity.id,
                    company_name = entity.company_name,
                    mobile_number = entity.mobile_number,
                    bank_name = entity.bank_name,
                    bank_branch = entity.bank_branch,
                    bank_cardno = entity.bank_cardno,
                    account_holder = entity.account_holder,
                    bank_province = (int)entity.bank_province,
                    bank_city = (int)entity.bank_city,
                    bank_country = (int)entity.bank_country,
                    status = (int)entity.status,
                    types = (int)entity.types,
                    remark = entity.remark,
                    company_permission = entity.company_permission,
                    bank_face_card = entity.bank_face_card,
                    bank_opposite_card = entity.bank_opposite_card
                };
            }
            else
            {
                return null;
            }
        }

        public BankCardDto GetBankCardInfoById(int id)
        {
            var entity = db.gw_shop_bankcards.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                return new BankCardDto()
                {
                    id = entity.id,
                    company_name = entity.company_name,
                    mobile_number = entity.mobile_number,
                    bank_name = entity.bank_name,
                    bank_branch = entity.bank_branch,
                    bank_cardno = entity.bank_cardno,
                    account_holder = entity.account_holder,
                    bank_province = (int)entity.bank_province,
                    bank_city = (int)entity.bank_city,
                    bank_country = (int)entity.bank_country,
                    status = (int)entity.status,
                    types = (int)entity.types,
                    remark = entity.remark,
                    company_permission = entity.company_permission,
                    bank_face_card = entity.bank_face_card,
                    bank_opposite_card = entity.bank_opposite_card
                };
            }
            else
            {
                return null;
            }
        }

        public IList<BankCardDto> GetShopBankCardByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, int status, string shopName, string companyName, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_shop_bankcards
                .Include(u => u.gw_shop)
                .Select(entity => new BankCardDto
                {
                    shop_name = entity.gw_shop.name,
                    id = entity.id,
                    company_name = entity.company_name,
                    mobile_number = entity.mobile_number,
                    bank_name = entity.bank_name,
                    bank_branch = entity.bank_branch,
                    bank_cardno = entity.bank_cardno,
                    account_holder = entity.account_holder,
                    bank_province = (int)entity.bank_province,
                    bank_city = (int)entity.bank_city,
                    bank_country = (int)entity.bank_country,
                    status = (int)entity.status,
                    types = (int)entity.types,
                    remark = entity.remark,
                    company_permission = entity.company_permission,
                    bank_face_card = entity.bank_face_card,
                    bank_opposite_card = entity.bank_opposite_card
                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(shopName))
            {
                list = list.Where(m => m.shop_name.Contains(shopName));
            }
            if (!string.IsNullOrWhiteSpace(companyName))
            {
                list = list.Where(m => m.company_name.Contains(companyName));
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            //list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderBy(m => m.status).ThenByDescending(i => i.id).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }
    }
}
